<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>投票</title>
    <meta name="description" content="投票" />
    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport"/>
    <meta name="format-detection" content="telephone=no">
    <link rel="stylesheet" href="./css/frozen.css">
    <link rel="stylesheet" href="./css/vote.css">
	<link class="dplayer-css" rel="stylesheet" href="./css/DPlayer.min.css">
    <link rel="stylesheet" href="../common/css/plugins.css" media="screen" title="no_title" charset="utf-8">
    <style>
        html,body{
            height: 0;
        }
        .voteListCon li{
            width: 44.5vw;
        }
        .voteListCon li .production{
            height: 25vw;
            padding-bottom: 0;
            background-size: contain;
        }
        .detailHeader .resource{
            display: block;
            width: 100%;
            margin-top: 10px;
            position: relative;
        }
        .detailHeader .resource img,.detailHeader .resource video,.detailHeader .resource audio{
            width: 100%;
            display: block;
            vertical-align: middle;
        }
        .detailHeader .resource video{
            height: 7.6rem;
        }
        .detailHeader .resource audio{
            position: absolute;
            bottom: 0;
        }
        .rule p{
            word-break: break-all;
        }
        .layui-m-layer0 .layui-m-layerchild{
            background-color: #e5cb86 !important;
        }
        .layui-m-layerbtn{
            background-color: #e5cb98 !important;
        }
        .layui-m-layerbtn span[yes]{
            color: #901d1d !important;
        }
        .layui-m-layerbtn span[no]{
            color: #901d1d !important;
        }
        .layui-m-layercont {
            color: #901d1d !important;
        }
        .ui-list-info{
            margin-left:8px;
            display: -webkit-box;
            display: -moz-box;
            display: -ms-flexbox;
            display: -webkit-flex;
            display: flex;
            -webkit-box-orient: vertical;
            -ms-box-orient: vertical;
            -moz-box-orient: vertical;
            -webkit-flex-flow: column nowrap;
            -ms-flex-flow: column nowrap;
            -moz-flex-flow: column nowrap;
            flex-flow: column nowrap;
        }
        .ui-list-info .state{
            display: flex;
            justify-content: space-between;
            align-items: flex-end;
            -webkit-align-items: flex-end;
            justify-content: space-between;
            -webkit-justify-content: space-between;
            flex: 1;display: flex;
            justify-content: space-between;
            align-items: flex-end;
            -webkit-align-items: flex-end;
            justify-content: space-between;
            -webkit-justify-content: space-between;
            flex: 1;
        }
        .voteList h3{
            text-align: left;
        }
        .voteBtnItem .ui-list-img{
            width: 44.5vw;
            height: 25vw;
            padding-bottom: 0;
            background-size: contain;
            background-color: #281010;
        }
        .voteBtnItem .ui-list-img i {
            width: 14%;
            padding-bottom: 14%;
            top: -7%;
            left: -7%;
        }
        .ui-list-info h4{
            font-size: .9rem;
        }
        .state .ranking{
            font-size: .8rem;
        }
        .state .votes{
            font-size: .8rem;
        }
        .voteBtnItem{
            position: relative;
        }
        .voteBtnItem .cover{
            width: 100%;
            position: absolute;
            bottom: 0;
            right: 0;
            left: 0;
            height: 24px;
            background: rgba(0,0,0,.4);
        }
        .voteBtnItem .cover span{
            display: block;
            width: 16px;
            height: 16px;
            margin: 4px 6px;
            /*-webkit-box-flex:1;-moz-box-flex:1;-webkit-flex:1;-ms-flex:1;flex:1*/
        }
        .voteBtnItem .cover span.play-icon{
            float: left;
            background: url(./img/play-icon.png) no-repeat center;
            background-size: contain;
        }
        .picCon.voteBtnItem .cover span.play-icon{
            float: left;
            background: url(./img/img-icon.png) no-repeat center;
            background-size: contain;
        }
        .voteBtnItem .cover span.checkbox-icon{
            float: right;
            /*background: url(./img/w-checkbox.png) no-repeat center;*/
            /*background-size: contain;*/
        }
        li.selected .voteBtnItem .cover span.checkbox-icon{
            background: url(./img/r-checkbox.png) no-repeat center;
            background-size: contain;
        }
        .voteBtnItem .cover span.checkbox-icon.selected{
            background: url(./img/r-checkbox.png) no-repeat center;
            background-size: contain;
        }
        .videoCon.hasImg:after,.audioCon.hasImg:after{
            background: none;
        }
        input::-webkit-input-placeholder { /* WebKit, Blink, Edge */
            color:#af4747 !important;
        }
        input:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
            color:#af4747 !important;
        }
        input::-moz-placeholder { /* Mozilla Firefox 19+ */
            color:#af4747 !important;
        }
        input:-ms-input-placeholder { /* Internet Explorer 10-11 */
            color:#af4747 !important;
        }
    </style>
    <script src="js/jquery.min.js"></script>
</head>
<body>
<div id="mainWrap"></div>
<script src="js/artTemplate/artTemplate.js"></script>
<script src="./js/DPlayer.min.js"></script>
<script src='js/vote-tpl.js'></script>
<script src="js/layer/layer.js"></script>
<script src="../common/js/appCall.js"></script>
<script type="text/javascript" charset="utf-8" src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script type="text/javascript" charset="utf-8" src="../common/js/weixinshare.js"></script>
<script>
    function QRCode(qrcode){
        var $mask = $('<div class="mask-layer">' +
            '             <div class="cover"></div>' +
            '             <div class="content">'+
//            '                 <div class="close icon"></div>' +
            '                 <div class="qr-code"></div>' +
            '                 <div class="slogan">扫描二维码,关注公众号后参与活动</div>' +
            '             </div>' +
            '         </div>');
        $mask.find('.close.icon').click(function(e){
            $mask.remove();
        });
        return {
            open: function(){
                if(qrcode){
                    $mask.find('.qr-code').html('<img src="'+qrcode+'" alt="二维码"/>');
                }
                $('body').append($mask);
            },
            close: function(){
                $mask.remove();
            }
        }
    }
    function forbidShare() {
        function onBridgeReady() {
            WeixinJSBridge.call('hideOptionMenu');
        }

        if (typeof WeixinJSBridge == "undefined") {
            if (document.addEventListener) {
                document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
            } else if (document.attachEvent) {
                document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
            }
        } else {
            onBridgeReady();
        }
    }
</script>
<script>
    window.addEventListener("popstate",function(e){
        window.location=window.location.href;
    })
    var isWechat = false,isAPP = false,isFollow = false,isCode=false,isPart=false,activities={},vote_token='';
    var url = '/',act_info='',appData={};
    window.parameter = GetRequest(window.location.href);
    //window.parameter.vote_id = 'ecefbde8-ac8f-41bf-b017-bb9b0e4e68d4';
    window.commonData = {};
    APPCall(function(data) {
        appData = data;
    });
    /*
     * 获取?后面的参数并返回 json 对象
     */
    function GetRequest(url) {
        if (!url || url.indexOf('?') == -1) {
            return {};
        }
        var url = url.split('?')[1].split('#')[0]; //获取url中"?"符后"#"前的字串
        var theRequest = new Object();
        var str = decodeURI(url);
        var strs;
        if (str.indexOf("&") != -1) {
            strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
            }
        } else {
            theRequest[str.split("=")[0]] = unescape(str.split("=")[1]);
        }
        theRequest['vote_id'] = theRequest['act_id'];

        return theRequest;
    }


    function bindEvent() {
        //IOS中激活a标签active事件
        var a = document.getElementsByTagName('a');
        for (var i = 0; i < a.length; i++) {
            a[i].addEventListener('touchstart', function () {
            }, false);
        }
        document.body.addEventListener('touchstart', function () {
        });

        $('#mainWrap').on('click', '.voteTab li', function () {

            var index = $(this).index();
            $(this).addClass('cur').siblings('li').removeClass('cur');
            $('.tabList').hide().eq(index).show();
            if (index == 2) {
                layer.open({type: 2, shadeClose: false});
                rankDateCallBack();
            }
        })
        $('body').on('click', '.closeItem', function () {
            layer.closeAll();
            if($('.ui-col.ui-flex.ui-flex-pack-center.cur').index()==2&&$(this).hasClass('productionBtn')){
                rankDateCallBack();
            }
        })

        //列表投票按钮触发事件
        $('#mainWrap').on('click', '.voteBtnItem', function () {
            //  	if((window.parameter['ways']!='wechat'&&!window.parameter.userid&&!window.parameter.uid) || (window.parameter.userid==null&&window.parameter.uid == null) ){
            //  		layer.open({
            //  			shadeClose:false,
            // 	className: 'messageStyle'
            // 	,content: '请下载APP参与投票'
            // });
            // setTimeout(function(){
            // 	window.location.href = window.location.origin+window.location.pathname+window.location.search+'&noLogin=true';
            // },1000)
            // return;
            //  	}
            layer.open({type: 2, shadeClose: false});
            var type = $(this).attr('voteType');
            var vId = $(this).attr('voteId');
            itemCallBack(vId, type);
        })

        //搜索按钮
        $('#mainWrap').on('click', '#searchBtn', function () {
            var query = $.trim($(this).prev('input').val());
            if(!query){
                layer.open({
                    className: 'messageStyle',
                    content: '搜索关键词不能为空'
                });
            }else{
                layer.open({type: 2, shadeClose: false});
                searchCallBack(query);
            }
        })

        //投票按钮
        $('body').on('click', '.voteBtn', function () {
            if (!isPart&&!window.parameter.uid && !window.parameter.mfSign) {
                if (activities.publishing.app.app_urls[0]) {
                    layer.open({
                        content: '请下载APP参与投票'
                        , btn: ['确定', '取消']
                        , yes: function (index) {
                            location.href = activities.publishing.app.app_urls[0];
                            layer.close(index);
                        }
                    });
                } else {
                    layer.open({
                        content: '请下载APP参与投票'
                        , btn: '确定'
                    });
                }
                return;
            }

            if (!isPart&&!window.parameter.uid && window.parameter.mfSign) {
                var paramJson = GetRequest(window.location.href);
                var param = '';
                //有noLogin参数
                if (window.location.search.indexOf('noLogin') != -1) {
                    $.each(paramJson, function (val, i) {
                        if (val != 'noLogin') {
                            param += val + '=' + paramJson[val] + '&'
                        }
                    })
                    param = param.slice(0, -1);
                    window.location.href = window.location.origin + window.location.pathname + '?' + param + '&noLogin=true';
                } else {//没noLogin参数
                    window.location.href = window.location.origin + window.location.pathname + window.location.search + '&noLogin=true';
                }
                return;
            }

            var item_id = $(this).attr('voteId');
            var uid = window.parameter.uid;
            voteCallBack(item_id, uid,$(this).hasClass('inlayer'));
            return false;
        })
    }
    //拼接content
    function joinContent(data){
        var html = '';
        for(var key in data.text){
            html += '<p>'+key+':'+data.text[key]+'</p>';
        }
        if(data['video']){
			for(var i =1,l= data.video.length;i<l;i++){
            html += '<div class="dplayer video-propotion">'+
               // '		<video controls poster="{{data.video[i].cover_url}}">' +
              //  '		   <source src="{{data.data.item.src}}" type="video/mp4">' +
               // '				您的浏览器不能使用最新的视频播放方式呢' +
               // '       </video>'+
                '    </div>';
        }
		}
        for(var j =0,l= data.img;j<l;j++) {
            html += '<div>' +
                '	    <img src="{{data.data.item.cover}}" alt="">' +
                '    </div>';
        }
//        for(var i =0,l= data.video;i++) {
//            html += '<div>' +
//                '       <audio  controls src="{{data.data.item.src}}">' +
//                '		    您的浏览器不能使用最新的视频播放方式呢' +
//                '		</audio>' +
//                '    </div>';
//        }
        return html;
    }


    /**
     * 验证sign
     */
    function signCallBack() {
        // var data = delete window.parameter.vote_id;
        //     data = delete data.noLogin;
//        layer.open({type: 2, shadeClose: false});
        var data = {};
        for (x in window.parameter) {
            if(x == 'vote_id'){
                continue;
            }
            data[x] = window.parameter[x]
        }

        $.ajax({
            url: url + 'api/app/sign/mf.php',
            data: data,
            type: 'get',
            success: function (ajaxData) {
                if (ajaxData.code == '200') {
                    vote_token = ajaxData.vote_token;
                    listDateCallBack();
                } else {
                    layer.open({
                        className: 'messageStyle'
                        , content: ajaxData.message
                    });
                }
            }
        })
    }
    function noUpdateSignCallBack() {
        var data = {};
        for (x in window.parameter) {
            if(x == 'vote_id'){
                continue;
            }
            data[x] = window.parameter[x]
        }

        $.ajax({
            url: url + 'api/app/sign/mf.php',
            data: data,
            type: 'get',
            success: function (ajaxData) {
                if (ajaxData.code == '200') {
                    vote_token = ajaxData.vote_token;
                } else {
                    layer.open({
                        className: 'messageStyle'
                        , content: ajaxData.message
                    });
                }
            }
        })
    }

    if(window.parameter['ways']!='wechat'){
        //没有uid 和 userid 不验签
        if (!window.parameter.userid && !window.parameter.uid) {
            listDateCallBack();
        } else {
            signCallBack();
        }
    }else{
        isSignPass = 1;
        vote_token = window.parameter['vote_token'];
        listDateCallBack();
    }
    function jugdeSignPass(){
        if(window.parameter['ways']!='wechat'&&(window.parameter.userid||window.parameter.uid)){
            noUpdateSignCallBack();
        }
    }
    /**
     * 获取投票列表数据
     * @return  {[type]}  [description]
     */
    function listDateCallBack() {
        $.ajax({
            url: url + 'lua/api/vote/details',
            data: {
                vote_id: window.parameter.vote_id
            },
            type: 'get',
            success: function (ajaxData) {
                layer.closeAll();
                if (ajaxData.code == '200') {
                    act_info = ajaxData.data.details;
                    //===============================
                    activities = ajaxData.data.details;
                    isWechat = (window.parameter.ways == 'wechat');//是否开启微信
                    isAPP = (activities.publishing.app.is_open =='on');//是否开启APP
                    isFollow = (window.parameter['following']!=1);//是否关注
                    isCode = Boolean(activities.publishing.wechat.qr_code[0]);//是否上传二维码
                    if(isWechat){
                        if(isFollow){
                            isPart = true;
                        }else{
                            if(isCode){
                                var qrCode = QRCode(activities.publishing.wechat.qr_code[0]).open();
                            }else{
                                isPart = true;
                            }
                        }
                    }else{
                        //APP
                    }
                    if (typeof wxshare != 'undefined' && (activities.shares.isopen == 'on' || activities.shares.isopen == '1')) {
                        var shareLink = '';
                        if(isWechat){
                            shareLink =window.location.origin+'/wechat/shares?id='+window.parameter.act_id;
                        }else{
                            shareLink = window.location.origin + location.pathname + '?act_id=' + wxshare.getUrlParam('act_id');
                        }
                        wxshare.share({
                            title: activities.shares.title,
                            desc: activities.shares.content,
                            link: shareLink,
                            imgUrl: activities.shares.thumb,
                        });
                    }else{
                        forbidShare();
                    }
                    //===========================
                    $('title').text(ajaxData.data.details.title);
                    if (ajaxData.data.details.categories.length > 0) {
                        //转换items的{} 为 [] 格式 方便模板遍历
                        var dealItems = [];
                        $.each(ajaxData.data.details.categories, function (i, val) {
                            if (ajaxData.data.details.items[val.id]) {
                                dealItems.push({
                                    group_name: val.title,
                                    data: ajaxData.data.details.items[val.id]
                                })
                            }

                        })
                        //供详情等页面用

                        ajaxData.data.details.dealItems = dealItems;
                        var data = ajaxData.data;
                        details = data.details;
                        tplHTML = voteTpl.mainHtml({
                            data: data
                        });
                    } else {
                        var data = ajaxData.data;
                        details = data.details;
                        tplHTML = voteTpl.mainHtml({
                            data: data
                        });
                    }

                    commonData = ajaxData.data.details;
                    $('#mainWrap').html(tplHTML);
                    $('#rules').html(details.rules);
                    bindEvent();
                } else {
                    layer.open({
                        className: 'messageStyle',
                        content: ajaxData.message,
                    });
                }
            }
        })
    }
    //listDateCallBack();


    /**
     * 获取排名列表数据
     * @return  {[type]}  [description]
     */
    function rankDateCallBack() {
        $.ajax({
            url: url + 'lua/api/vote/rank',
            data: {
                vote_id: window.parameter.vote_id
            },
            type: 'get',
            success: function (ajaxData) {
                layer.closeAll();
                if (ajaxData.code == '200') {
                    var tplHTML = voteTpl.rank({
                        data: ajaxData
                    });
                    $('#rankBox').html(tplHTML);
                } else {
                    layer.open({
                        className: 'messageStyle'
                        , content: ajaxData.message
                    });
                }
            }
        })
    }

    /**
     * 投票详情
     * item_id : 候选项的id
     * type : 详情类型 1 图片 2 音频 3 视频 4 外链
     */
    function itemCallBack(item_id, type) {
        $.ajax({
            url: url + 'lua/api/vote/item',
            data: {
                'vote_id': window.parameter.vote_id,
                'id': item_id
            },
            type: 'get',
            success: function (ajaxData) {
                layer.closeAll();
                if (ajaxData.code == '200') {
                    window.history.pushState("", "vote", window.location.search);
                    // var tplHTML = voteTpl.rank({data:ajaxData});
                    // $('#rankBox').html(tplHTML);
                    var contentJson = {};
                    if(ajaxData.data.item.from==3){
                        contentJson = JSON.parse(ajaxData.data.item.content);
                        ajaxData.data.item.content = joinContent(contentJson);
                    }
                    layer.open({
                        type: 1,
                        content: '<div style="background-color:#fff;height:' + $(window).height() + 'px"><i class="closeItem" ></i>' + voteTpl['items' + type]({
                            data: {data: ajaxData.data, commonData: window.commonData}
                        }) + '</div>',
                        style: 'position:absolute; bottom:0; left:0; width: 100%; height:100%; padding:0; border:none;overflow: auto;',
                        success:function() {
                            var videoListWrap = $(".dplayer");
                            if (videoListWrap.length > 0) {
                                for (var i = 0, len = videoListWrap.length; i < len; i++) {
                                    new DPlayer({
                                        container: videoListWrap[i],
                                        video: {
                                            url: contentJson.video[i+1].resource_url,
                                            pic: contentJson.video[i+1].cover_url
                                        }
                                    });
                                }
                            }
                            if (type == 3) {
                                var videoWrap = $("#dplayer");
                                new DPlayer({
                                    container: videoWrap[0],
                                    video: {
                                        url: ajaxData.data.item.src,
                                        pic: ajaxData.data.item.cover
                                    }
                                });
                            }
                            $(".dplayer-full-icon").hide();
								$(".dplayer-full-in-icon").click(function(){
									setTimeout(function(){
										if($(".dplayer-fulled").length > 0){
											$(".layui-m-layerchild")[0].scrollTop = 0;
											layerFullScreen(true);
										}else{
											layerFullScreen(false);
										}
									},500);
									
								});
                        }
					});
                } else {
                    layer.open({
                        className: 'messageStyle'
                        , content: ajaxData.message
                    });
                }
            }
        })
    }
	function layerFullScreen(isFull){
		if(isFull){
			$(".layui-m-layerchild").css({width:"100vw",height:"100vh",overflow:"hidden"});
		}else{
			$(".layui-m-layerchild").css({width:"100%",height:"100%",overflow:"auto"}) 
		}
		
	}
    function updateItemCallBack(item_id) {
        var params = {
            vote_id: window.parameter.vote_id,
            id: item_id,
        };
        var postData = $.extend({},window.parameter,params);
        $.ajax({
            url: url + 'lua/api/vote/item',
            data: postData,
            type: 'get',
            success: function (ajaxData) {
                if (ajaxData.code == '200') {
                    $('#vote1_' + ajaxData.data.item.id).html(parseInt($('#vote1_' + ajaxData.data.item.id).html()) + 1);
                    $('#vote_' + ajaxData.data.item.id).html(parseInt($('#vote_' + ajaxData.data.item.id).html()) + 1 + "票");
                    $('#vote_num_' + ajaxData.data.item.id).html(parseInt(ajaxData.data.rank));

                } else {
                    layer.open({
                        className: 'messageStyle'
                        , content: ajaxData.message
                    });
                }
            }
        })
    }

    /**
     * 投票详情
     * `q`: 关键字 （只能完全匹配）
     */
    function searchCallBack(q) {
        $.ajax({
            url: '/api/vote/'+window.parameter.act_id+'/search',
            data: {
                'q': q
            },
            type: 'get',
            success: function (data) {
                if(data.code==200){
                    var obj = {
                        'vote_id':  window.parameter.act_id,
                        'act_id': window.parameter.act_id,
                        'ids': data.data.ids
                    };
                    $.ajax({
                        type: 'POST',
                        url: url + 'lua/api/vote/search',
                        data: JSON.stringify(obj),
                        dataType: 'json',
                        contentType: "application/json; charset=utf-8",
                        success: function (ajaxData) {
                            layer.closeAll();
                            if (ajaxData.code == 200) {
                                var tplHTML = voteTpl.search({
                                    data: ajaxData.data
                                });
                                $('#searchBox').html(tplHTML);
                            } else {
                                $('#searchBox').html('<p class="noResults">' + ajaxData.message + '</p>');
                                //             layer.open({
                                // 	className: 'messageStyle'
                                // 	,content: ajaxData.message
                                // });
                            }
                        }
                    })
                }else{
                    layer.open({
                        className: 'messageStyle',
                        content: data.message
                    });
                }
            }
        });
    }
    /**
     * 投票
     *  `item_id`: 候选项的id
     *  `uid`: 用户id
     */
    function voteCallBack(item_id, uid, inlayer) {
        var index = layer.open({type: 2, shadeClose: false});
        var device_id = '',ip='',locations='';
        if(!$.isEmptyObject(appData)){
            device_id = appData['deviceInfo']['deviceId'];
            ip = appData['deviceInfo']['ipAddress'];
            locations = appData['userLocation']['locationName'];
        }
        var postData = {
            'vote_id': window.parameter.act_id,
            'item_id': item_id,
            'uid': window.parameter.uid,
            'device_id': device_id,
            'ip': ip,
            'location': locations,
            'vote_token': vote_token
        };
        postData = $.extend({},postData,window.parameter);
        $.ajax({
            url: url + 'lua/api/vote/vote',
            data: postData,
            type: 'get',
            success: function (ajaxData) {
                layer.close(index);
                if (ajaxData.code == 200) {
                    if(!inlayer){
                        $('#vote1_' + item_id).html(parseInt($('#vote1_' + item_id).html()) + 1);
                        $('#vote2_' + item_id).html(parseInt($('#vote2_' + item_id).html()) + 1);
                        $('#vote_' + item_id).html(parseInt($('#vote_' + item_id).html()) + 1 + "票");
                        layer.open({
                            time: 1,
                            className: 'messageStyle'
                            , content: ajaxData.message
                        });
                    }else{
                        layer.open({
                            time: 1,
                            className: 'messageStyle'
                            , content: ajaxData.message
                        });
                        updateItemCallBack(item_id);
                    }
                } else {
                    layer.open({
                        className: 'messageStyle'
                        , content: ajaxData.message
                    });
                }
                jugdeSignPass();
            }
        })
    }
</script>
</body>

</html>
